package com.uking.helper;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;

public class VKNetBossUtils {
    private static final String CIPHER_DESC = "DESede/ECB/PKCS5Padding";
    private static final String DES = "DESede";
    private static final String PADDING = "0";

    public static String decrypt(String message, String key) {
        try {
            byte[] bytes = hex2byte(message);
            Cipher cipher = Cipher.getInstance(CIPHER_DESC);
            cipher.init(2, genSecretKey(key));
            return new String(cipher.doFinal(bytes));
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    public static String encrypt(String message, String key) {
        try {
            Cipher cipher = Cipher.getInstance(CIPHER_DESC);
            cipher.init(1, genSecretKey(key));
            return byte2hex(cipher.doFinal(message.getBytes()));
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    private static SecretKey genSecretKey(String key) throws Exception {
        return SecretKeyFactory.getInstance(DES).generateSecret(new DESedeKeySpec(StringTools.rightPad(key, 24, PADDING).getBytes()));
    }

    public static String byte2hex(byte[] bytes) {
        StringBuffer buffer = new StringBuffer();
        for (byte b : bytes) {
            buffer.append(StringTools.leftPad(Integer.toHexString(b & 255), 2, PADDING));
        }
        return buffer.toString().toUpperCase();
    }

    public static byte[] hex2byte(String hex) {
        int length = hex.length();
        byte[] bytes = new byte[(length / 2)];
        for (int i = 0; i < length / 2; i++) {
            bytes[i] = (byte) Integer.parseInt("" + hex.charAt(i * 2) + hex.charAt((i * 2) + 1), 16);
        }
        return bytes;
    }
}
